package com.aiti.lulian.controller;

import cn.hutool.core.util.StrUtil;
import com.aiti.base.core.base.controller.WebController;
import com.aiti.base.core.utils.message.Message;
import com.aiti.lulian.dto.LuLianOfferDto;
import com.aiti.lulian.entity.LuLianEnterprise;
import com.aiti.lulian.entity.LuLianEnterpriseUser;
import com.aiti.lulian.entity.LuLianOffer;
import com.aiti.lulian.entity.message.OfferMessage;
import com.aiti.lulian.service.*;
import com.aiti.lulian.vo.LuLianOfferVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @ClassName LuLianOfferController
 * @Description 报价表controller
 * @Author diaozhende
 * @Date 2024/6/19 0019 11:01
 */
@RestController
@RequestMapping("offer")
public class LuLianOfferController extends WebController {
    protected final Logger logger = LoggerFactory.getLogger(LuLianOfferController.class);

    @Resource
    private ILuLianOfferService offerService;

    @Resource
    private IOfferMessageService offerMessageService;

    @Autowired
    private ILuLianEnterpriseUserService enterpriseUserService;

    @Autowired
    private ILuLianEnterpriseService enterpriseService;

    /**
     * 查询报价的各种计数
     *
     * @param
     * @return com.aiti.base.core.utils.message.Message
     * @date 2024/7/4 15:54
     * @author WongMZ
     */
    @GetMapping("/queryCount/{offerUserId}")
    public Message queryCount(@PathVariable("offerUserId") String offerUserId) {
        try {
            if (StrUtil.isBlank(offerUserId)) {
                logger.error("查询异常：===》入参异常");
                return Message.fail("入参异常");
            }
            return Message.success(offerService.queryCount(offerUserId));
        } catch (Exception e) {
            logger.error("查询异常：===》" + e);
            return Message.fail(e.getMessage());
        }
    }

    /**
     * 保存
     *
     * @param luLianOffer 报价参数
     * @return com.aiti.base.core.utils.message.Message
     * @date 2024/6/19 0019 11:03
     * @author diaozhende
     */
    @PostMapping
    public Message save(@RequestBody LuLianOffer luLianOffer) {
        offerService.save(luLianOffer);
        return Message.success();
    }

    /**
     * 发布报价单
     *
     * @param luLianOfferDto 参数
     * @return com.aiti.base.core.utils.message.Message
     * @date 2024/07/30
     * @author WongMz
     */
    @PostMapping("/save")
    public Message saveOffer(@RequestBody LuLianOfferDto luLianOfferDto) {
        try {
            if (luLianOfferDto == null) {
                logger.error("新增异常：===》入参异常");
                return Message.fail("入参异常");
            }
            //检查当前是否为已登录状态
            String userId = findUserId();
            if (StrUtil.isBlank(userId)) {
                userId = luLianOfferDto.getUserId();
                if (StrUtil.isBlank(userId)) {
                    System.out.println("------------------未登录------------------");
                    return Fail("请先注册/登录！");
                }
            }
            luLianOfferDto.setCreator(userId);
            //检查是否为已认证企业的账号
            LambdaQueryWrapper<LuLianEnterpriseUser> enterpriseUserWrapper = new LambdaQueryWrapper<>();
            enterpriseUserWrapper.eq(LuLianEnterpriseUser::getUserId, userId);
            List<LuLianEnterpriseUser> enterpriseUserList = enterpriseUserService.list(enterpriseUserWrapper);
            List<String> enterpriseIds = enterpriseUserList.stream().map(LuLianEnterpriseUser::getEnterpriseId).collect(Collectors.toList());
            if (enterpriseIds == null || enterpriseIds.size() == 0) {
                enterpriseIds.add("0");
            }
            LambdaQueryWrapper<LuLianEnterprise> enterpriseWrapper = new LambdaQueryWrapper<>();
            enterpriseWrapper.in(LuLianEnterprise::getBaseId, enterpriseIds);
            int count = enterpriseService.count(enterpriseWrapper);
            if (count == 0) {
                return Fail("该账号未认证企业，请先进行企业认证！");
            } else if (count == 1 && enterpriseUserList.size() > 1) {
                return Fail("该账号的企业关联记录存在多条！");
            } else if (count > 1) {
                return Fail("该账号关联了多个认证企业！");
            }
            //进行数据保存
            int res = offerService.saveOffer(luLianOfferDto);
            if (res > 0){
                return Message.success();
            }else if (res == 0){
                return Message.fail();
            } else {
                return Message.fail("报价消息创建失败");
            }
        } catch (Exception e) {
            logger.error("新增异常：===》" + e);
            return Message.fail(e.getMessage());
        }
    }

    /**
     * 查询报价列表（条件、分页）
     *
     * @param
     * @return com.aiti.base.core.utils.message.Message
     * @date 2024/7/3 15:41
     * @author WongMZ
     */
    @GetMapping("/queryList")
    public Message queryOfferListPage(LuLianOfferDto luLianOfferDto) {
        try {
            if (luLianOfferDto == null) {
                logger.error("查询异常：===》入参异常");
                return Message.fail("入参异常");
            }
            String userId = findUserId();
            if (StrUtil.isNotBlank(userId)) {
                luLianOfferDto.setCreator(userId);
            } else {
                System.out.println("------------------未登录------------------");
                return Fail("请先注册/登录！");
            }
            Page<LuLianOffer> page = startPage(luLianOfferDto.getPageNum(), luLianOfferDto.getPageSize());
            return Message.success(offerService.queryOfferListPage(page, luLianOfferDto));
        } catch (Exception e) {
            logger.error("查询异常：===》" + e);
            return Message.fail(e.getMessage());
        }
    }

    /**
     * 根据baseId删除报价记录
     *
     * @param
     * @return com.aiti.base.core.utils.message.Message
     * @date 2024/7/3 16:45
     * @author WongMZ
     */
    @DeleteMapping("/{baseId}")
    public Message deleteOfferByBaseId(@PathVariable("baseId") String baseId) {
        try {
            if (StrUtil.isBlank(baseId)) {
                logger.error("删除异常：===》入参异常");
                return Message.fail("入参异常");
            }
            if (!offerService.removeById(baseId)) {
                return Message.success();
            } else {
                return Message.fail();
            }
        } catch (Exception e) {
            logger.error("删除异常：===》" + e);
            return Message.fail(e.getMessage());
        }
    }

    /**
     * 根据baseId修改报价记录
     *
     * @param
     * @return com.aiti.base.core.utils.message.Message
     * @date 2024/7/3 17:00
     * @author WongMZ
     */
    @PutMapping
    public Message updateOfferByBaseId(@RequestBody LuLianOffer luLianOffer) {
        try {
            if (luLianOffer == null) {
                logger.error("更新异常：===》入参异常");
                return Message.fail("入参异常");
            }
            if (!offerService.updateOfferByBaseId(luLianOffer)) {
                return Message.success();
            } else {
                return Message.fail();
            }
        } catch (Exception e) {
            logger.error("更新异常：===》" + e);
            return Message.fail(e.getMessage());
        }
    }

    /**
     * 查询报价消息
     * @date 2024/08/07
     * @author WongMz
     */
    @GetMapping("/message")
    public Message queryOfferMessage(@RequestParam("userId") String userId) {
        try {
            if (StrUtil.isBlank(userId)) {
                logger.error("查询异常：===》入参异常");
                return Message.fail("入参异常");
            }
            return Message.success(offerMessageService.queryOfferMessage(userId));
        } catch (Exception e) {
            logger.error("查询异常：===》" + e);
            return Message.fail(e.getMessage());
        }
    }

    /**
     * 修改报价消息的状态
     * @date 2024/08/07
     * @author WongMz
     */
    @PutMapping("/message")
    public Message updateOfferMessage(OfferMessage message) {
        try {
            if (message == null) {
                logger.error("修改异常：===》入参异常");
                return Message.fail("入参异常");
            }
            LambdaUpdateWrapper<OfferMessage> wrapper = new LambdaUpdateWrapper<>();
            wrapper.set(StrUtil.isNotBlank(message.getIsRead()), OfferMessage::getIsRead, message.getIsRead());
            boolean res = offerMessageService.update(message, wrapper);

            if (res) {
                return Message.success();
            } else {
                return Message.fail();
            }
        } catch (Exception e) {
            logger.error("修改异常：===》" + e);
            return Message.fail(e.getMessage());
        }
    }

    /**
     * 查询别人给自已的报名询价列表
     * @param luLianOfferDto
     * @return
     */
    @GetMapping("/getRegisteredInquiryDataList")
    public Message getRegisteredInquiryDataList(LuLianOfferDto luLianOfferDto) {
        String userId = findUserId();
        Integer pageSize = luLianOfferDto.getPageSize();
        Integer pageNum = luLianOfferDto.getPageNum();
        Page<LuLianOffer> page = startPage(pageNum, pageSize);
        List<LuLianOfferVo> list = offerMessageService.getRegisteredInquiryDataList(page,userId);
        return Message.success(this.getPageResult(list, pageNum, pageSize, (int)page.getTotal()));
    }
}
